package com.sh.config.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 *
 * NOTE：权限拦截器
 *
 * @author： king
 * @date： 2019年3月31日
 *
 */
public class AuthInterceptor implements HandlerInterceptor {

	private static final Logger log = Logger.getLogger(AuthInterceptor.class);

	private List<String> excludeUrls;

	public List<String> getExcludeUrls() {

		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {

		this.excludeUrls = excludeUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers","X-Requested-With, Content-Type, Authorization");
		response.setHeader("Access-Control-Allow-Methods","GET, POST");

		// 用户访问的资源地址
		String requestPath = getRequestPath(request);
		log.info("requestPath:" + requestPath);

		return true;
	}

	/**
	 * 截取访问路径
	 *
	 * @param request
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {

		String requestPath = request.getRequestURI();

		String signA = "&";
		String signB = ";";

		// 去掉其他参数
		if (requestPath.indexOf(signA) > -1) {

			requestPath = requestPath.substring(0, requestPath.indexOf(signA));
		}
		// 去掉jsessionid参数
		if(requestPath.indexOf(signB) > -1){

			requestPath = requestPath.substring(0, requestPath.indexOf(signB));
		}

		// 去掉项目路径
		requestPath = requestPath.substring(request.getContextPath().length() + 1);
		return requestPath;
	}
}
